package com.huangliusong.threadcurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author huangliusong
 * @since 2018/11/21
 * {@link }
 */
@Slf4j
public class CyclicBarrierExample2 {
    private static CyclicBarrier cyclicBarrier=new CyclicBarrier(5);
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService=Executors.newCachedThreadPool();

        for (int i=0;i<10;i++){
            final int threadNum=i;
            Thread.sleep(1000);
            executorService.execute(()->{
                try {
                    read1(threadNum);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("{}",e);
                }
            });
        }
    }

    public static void  read1(int i) throws Exception {
        Thread.sleep(1000);
        log.info("{} is read",i);
        try{
            cyclicBarrier.await(2000,TimeUnit.MILLISECONDS);
        }catch (BrokenBarrierException | TimeoutException e){
            log.warn("e{}",e);
        }

        log.info("{}continue",i);
    }
}
